
import 'package:reabampos/src/reabam/operation/rb_api.dart';
import 'package:reabampos/src/reabam/ui/pagestate_main_webview.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';

/*
h5api缓存
 */
class SupportH5ApiCache{

  MainWebViewStatePage statePage;

  SupportH5ApiCache(this.statePage);

  //////////////////////////////////////////////

  void h5ApiRequestCache(dynamic data){

    try{

      Map<String,dynamic> request;
      if(data is String){
        request=XJsonUtils.json2Map(data)??{};
      }else{
        request=data??{};
      }

      String key=request['skey']??'XSDK';
      String apiUrl=request['api'];
      String requestBody=request['param'].toString();

      //
      String cacheJson=XSharePreferencesUtils.getString(key);
      Map<String,dynamic> obj=XJsonUtils.json2Map(cacheJson);

      Map<String,dynamic> map={};
      map['sKey']=key;
      map['data']=obj;
      statePage.runJSFunction(statePage.jsFunction_getAppValue("initConfig",XJsonUtils.obj2Json(map)));

      RBBaseApi.h5RequestApiCommon(
          url: apiUrl,
          json: requestBody,
          key: key,
          succeed: (String response, Map<String, dynamic> responseMap, Map<String, dynamic> headersResponse) {

            //更新保存
            XSharePreferencesUtils.saveString(key,XJsonUtils.obj2Json(responseMap));

            //请求成功,再通知多一次h5
            Map<String,dynamic> map={};
            map['sKey']=key;
            map['data']=responseMap;
            statePage.runJSFunction(statePage.jsFunction_getAppValue("initConfig",XJsonUtils.obj2Json(map)));

          });

    }catch(e){
      XLogUtils.printLog('$e');
    }
  }
}